package org.JQbitorrentClinet.utils;

import com.google.gson.Gson;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;

import java.lang.reflect.Type;

@Slf4j
public class Utils {
        public static <T> T convertEntity(CloseableHttpResponse response,Type type) {
            try {
                String content = EntityUtils.toString(response.getEntity());
                if(type == String.class)
                    return (T) content;

                Gson gson = new Gson();
                if (content.equals("[]"))
                    return null;

                T result = gson.fromJson(content, type);
                 return result;
            } catch (Exception e) {
                log.error("Convert Entity Error", e);
                return null;
            }
        }

        @SneakyThrows
        public static boolean responseCheck(CloseableHttpResponse response) {
            log.trace("ResponseStatus:", response.getStatusLine());
            if (response.getStatusLine().getStatusCode() != 200)
                throw new RuntimeException(EntityUtils.toString(response.getEntity()));

            return true;
        }

        public static String parseCookie(String cookie) {
            String[] cookies = cookie.split(";");
            for (String c : cookies) {
                if (c.contains("SID")) {
                    return c;
                }
            }
            return null;
        }
}
